package com.agileai.portal.portlets.reviews;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.bizmoduler.reviews.WcmInfoReviewManage;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.portlets.BaseMashupPortlet;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
/**
 * generated by miscdp
 */
public class ReviewListDisplayPortlet extends BaseMashupPortlet {
	
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);

		String contentIdParamKey = preferences.getValue("contentIdParamKey", null);
	    String contentIdDefValue = preferences.getValue("contentIdDefValue", null);

	    HttpServletRequest httpServletRequest = PortletRequestHelper.getRequestContext(request).getServletRequest();
	    String contentId = httpServletRequest.getParameter(contentIdParamKey);
	    if (StringUtil.isNullOrEmpty(contentId)) {
	    	contentId = contentIdDefValue;
	    }
      
	    if (StringUtil.isNullOrEmpty(contentId)) {
	    	request.setAttribute("content", "content is not defined,please check it !");
	    }
	    DataParam param = new DataParam();
	    param.put("INFO_ID",contentId);
	    List<DataRow> rsList = getService().findRecords(param);
		request.setAttribute("total", rsList.size());
	    request.setAttribute("contentId", contentId);
	    request.setAttribute("portletId", request.getWindowID());
	    super.doView(request, response);
	}

	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String template = preferences.getValue("template", null);
		String contentIdParamKey = preferences.getValue("contentIdParamKey", null);
		String contentIdDefValue = preferences.getValue("contentIdDefValue", null);
		
		request.setAttribute("template", template);
		request.setAttribute("contentIdDefValue", contentIdDefValue);
		request.setAttribute("contentIdParamKey", contentIdParamKey);
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		
		String template = request.getParameter("template");
		String contentIdParamKey = request.getParameter("contentIdParamKey");
		String contentIdDefValue = request.getParameter("contentIdDefValue");

		PreferencesWrapper preferWapper = new PreferencesWrapper();			
		preferWapper.setValue("template", template);
		preferWapper.setValue("contentIdParamKey", contentIdParamKey);
		preferWapper.setValue("contentIdDefValue", contentIdDefValue);
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences()); 
		
		response.setPortletMode(PortletMode.VIEW);
	}
	

	@Resource(id="getAjaxData")
	public void getAjaxData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String html = "";
		try {
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			String template = preferences.getValue("template", null);
		    String contentId = request.getParameter("contentId");
			int pageNum = Integer.parseInt(request.getParameter("pageNum"));
			int pageSize = Integer.parseInt(request.getParameter("pageSize"));
			if (template != null){
				if (template.startsWith("http://")){
					template = this.retrieveTemplate(request, template);
				}
				
				DataParam param = new DataParam();
			    param.put("INFO_ID",contentId);
			    
			    DataRow infoRow = getService().getInfoRecord(param);
			    JSONObject jsonObject = new JSONObject();
			    jsonObject.put("infoId",contentId);
			    jsonObject.put("infoTitle",infoRow.getString("INFO_TITLE"));
			    JSONArray jsonArray = new JSONArray();
			    String fields[] = {"REW_ID","REW_CONTENT","REW_TIME","USER_CODE","REW_ANONYMITY","INFO_ID","REW_IPADDRESS","floor","imgUrl"};
				List<DataRow> rsList = getService().findRecords(param);
				jsonObject.put("reviewCount",rsList.size());
				if(rsList.size()>0){
					int max = 0;
					if((pageNum+1)*pageSize>rsList.size()){
						max = rsList.size();
					}else{
						max = (pageNum+1)*pageSize;
					}
					for(int i=pageNum*pageSize; i<max;i++){
						DataRow row = rsList.get(i);
						Timestamp aaa = row.getTimestamp("REW_TIME");
						Date date = new Date(aaa.getTime());
						String sdate = DateUtil.format(10, date);
						row.put("REW_TIME", sdate);
						String anonymity = row.stringValue("REW_ANONYMITY");
						if(anonymity.equals("1")){
							row.put("REW_ANONYMITY", "匿名用户");
							row.put("imgUrl", "user_anonymous.png");
						}else{
							row.put("REW_ANONYMITY",row.stringValue("USER_CODE"));
							row.put("imgUrl", "user_logined.png");
						}
						String floor = String.valueOf(rsList.size()-i);
						row.put("floor", floor);
						JSONObject object = new JSONObject();
						for(int j=0;j<fields.length;j++){												
							object.put(fields[j], row.stringValue(fields[j]));
						}
						jsonArray.put(object);
					}
				}
				jsonObject.put("datas", jsonArray);
				String ajaxData = jsonObject.toString();
				html = mergeReviewData(ajaxData, template);	
			}
		} catch (Exception e) {
			this.logger.error("获取数据失败getAjaxData", e);
		}				
		PrintWriter writer = response.getWriter();
		writer.print(html);
		writer.close();
	}
	
	private String retrieveTemplate(PortletRequest request, String dataURL) {
		String result = "";
		try {
			int index = dataURL.lastIndexOf("=");
			String templateId = dataURL.substring(index+1,dataURL.length());
			result = PortletCacheManager.getOnly().getCachedData("Y",templateId,dataURL, "0");
		} catch (Exception e) {
			this.logger.error("retrieve template error ", e);
		}
		return result;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String mergeReviewData(String ajaxData,String template){
		String result = null;
		try {
			StringWriter writer = new StringWriter();
			
			String encoding = "utf-8";
	    	Configuration cfg = new Configuration();
	    	cfg.setTemplateLoader(new StringTemplateLoader(template));  
	    	cfg.setEncoding(Locale.getDefault(), encoding);
	        cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
	    	Template temp = cfg.getTemplate("");
	    	temp.setEncoding(encoding);
	        Map root = new HashMap();
	        root.put("text",ajaxData);
	        temp.process(root, writer);
	        writer.flush();
	        result = writer.toString();
		} catch (Exception e) { 
			e.printStackTrace();
			result = "";
		}
		return result;
	}

	private WcmInfoReviewManage getService() {
		WcmInfoReviewManage wcmInfoReviewManageService = (WcmInfoReviewManage) BeanFactory.instance().getBean("wcmInfoReviewManageService");
		return wcmInfoReviewManageService;
	}
}
